{% extends "base.html" %}

{% block title %}密码管理 - 生活助手{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1><i class="bi bi-shield-lock"></i> 密码管理器</h1>
            <p class="text-muted">安全管理您的账号密码</p>
        </div>
        <div>
            <button class="btn btn-primary btn-custom me-2" data-bs-toggle="modal" data-bs-target="#addPasswordModal" id="btn-add-password" style="display:none;">
                <i class="bi bi-plus-circle"></i> 添加密码
            </button>
            <button class="btn btn-danger btn-custom" onclick="logout()" id="btn-logout" style="display:none;">
                <i class="bi bi-box-arrow-right"></i> 退出
            </button>
        </div>
    </div>
</div>

<!-- 主密码验证区域 -->
<div id="auth-area">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card custom-card">
                <div class="card-body text-center p-5">
                    <i class="bi bi-shield-check text-primary" style="font-size: 4rem;"></i>
                    <h3 class="mt-3 mb-4" id="auth-title">请验证主密码</h3>
                    <p class="text-muted mb-4" id="auth-description">输入您的主密码以访问密码管理器</p>
                    
                    <div class="mb-3">
                        <input type="password" class="form-control form-control-lg" id="master-password-input" 
                               placeholder="输入主密码">
                    </div>
                    
                    <button class="btn btn-primary btn-lg btn-custom" onclick="verifyOrSetMaster()" id="auth-button">
                        验证
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 密码管理区域 -->
<div id="password-area" style="display:none;">
    <!-- 过滤和搜索 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <select class="form-select" id="filter-category" onchange="loadPasswords()">
                        <option value="">所有分类</option>
                        <option value="邮箱">邮箱</option>
                        <option value="银行">银行</option>
                        <option value="社交">社交</option>
                        <option value="购物">购物</option>
                        <option value="工作">工作</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <input type="text" class="form-control" id="search-password" 
                           placeholder="搜索网站或用户名..." oninput="loadPasswords()">
                </div>
            </div>
        </div>
    </div>
    
    <!-- 密码列表 -->
    <div id="password-list">
        <p class="text-center text-muted">加载中...</p>
    </div>
</div>

<!-- 添加密码模态框 -->
<div class="modal fade" id="addPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="add-password-form">
                    <div class="mb-3">
                        <label class="form-label">网站/服务名称 *</label>
                        <input type="text" class="form-control" id="password-website" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户名/邮箱 *</label>
                        <input type="text" class="form-control" id="password-username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码 *</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="password-password" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('password-password')">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                        <div id="password-strength" class="mt-2"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">分类</label>
                        <select class="form-select" id="password-category">
                            <option value="邮箱">邮箱</option>
                            <option value="银行">银行</option>
                            <option value="社交">社交</option>
                            <option value="购物">购物</option>
                            <option value="工作">工作</option>
                            <option value="其他" selected>其他</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">网站URL</label>
                        <input type="url" class="form-control" id="password-url" placeholder="https://">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">备注</label>
                        <textarea class="form-control" id="password-notes" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addPassword()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 查看密码模态框 -->
<div class="modal fade" id="viewPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">密码详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="text-muted">网站/服务</label>
                    <p class="fw-bold" id="view-website"></p>
                </div>
                <div class="mb-3">
                    <label class="text-muted">用户名/邮箱</label>
                    <p class="fw-bold" id="view-username"></p>
                </div>
                <div class="mb-3">
                    <label class="text-muted">密码</label>
                    <div class="input-group">
                        <input type="password" class="form-control" id="view-password" readonly>
                        <button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('view-password')">
                            <i class="bi bi-eye"></i>
                        </button>
                        <button class="btn btn-outline-primary" type="button" onclick="copyPassword()">
                            <i class="bi bi-clipboard"></i> 复制
                        </button>
                    </div>
                </div>
                <div class="mb-3" id="view-url-container" style="display:none;">
                    <label class="text-muted">网站URL</label>
                    <p><a href="#" id="view-url" target="_blank"></a></p>
                </div>
                <div class="mb-3" id="view-notes-container" style="display:none;">
                    <label class="text-muted">备注</label>
                    <p id="view-notes"></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentPasswords = [];
let masterAuthenticated = false;

// 检查主密码状态
function checkMasterPassword() {
    fetch('/password/api/check-master')
        .then(response => response.json())
        .then(data => {
            if (!data.exists) {
                // 首次使用，需要设置主密码
                document.getElementById('auth-title').textContent = '设置主密码';
                document.getElementById('auth-description').textContent = '首次使用，请设置一个主密码（至少8个字符）';
                document.getElementById('auth-button').textContent = '设置';
            } else if (data.authenticated) {
                // 已验证，显示密码管理区域
                showPasswordArea();
            }
        });
}

// 验证或设置主密码
function verifyOrSetMaster() {
    const masterPassword = document.getElementById('master-password-input').value;
    
    if (!masterPassword) {
        showAlert('请输入主密码', 'warning');
        return;
    }
    
    if (masterPassword.length < 8) {
        showAlert('主密码至少8个字符', 'warning');
        return;
    }
    
    const authButton = document.getElementById('auth-button');
    const isSetMode = authButton.textContent === '设置';
    const url = isSetMode ? '/password/api/set-master' : '/password/api/verify-master';
    
    fetch(url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ master_password: masterPassword })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(data.message, 'success');
            showPasswordArea();
        } else {
            showAlert(data.error || '验证失败', 'danger');
        }
    })
    .catch(error => {
        showAlert('操作失败', 'danger');
    });
}

// 显示密码管理区域
function showPasswordArea() {
    masterAuthenticated = true;
    document.getElementById('auth-area').style.display = 'none';
    document.getElementById('password-area').style.display = 'block';
    document.getElementById('btn-add-password').style.display = 'inline-block';
    document.getElementById('btn-logout').style.display = 'inline-block';
    loadPasswords();
}

// 退出登录
function logout() {
    fetch('/password/api/logout', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            location.reload();
        });
}

// 加载密码列表
function loadPasswords() {
    const category = document.getElementById('filter-category').value;
    const search = document.getElementById('search-password').value;
    
    let url = '/password/api/passwords?';
    if (category) url += `category=${category}&`;
    if (search) url += `search=${search}`;
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            currentPasswords = data.passwords;
            renderPasswords();
        });
}

// 渲染密码列表
function renderPasswords() {
    const container = document.getElementById('password-list');
    
    if (currentPasswords.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">暂无密码记录</p>';
        return;
    }
    
    container.innerHTML = currentPasswords.map(pwd => `
        <div class="card custom-card mb-3">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <h5 class="mb-1">
                            <i class="bi bi-globe"></i> ${pwd.website}
                            <span class="badge bg-secondary ms-2">${pwd.category}</span>
                        </h5>
                        <p class="text-muted mb-1">
                            <i class="bi bi-person"></i> ${pwd.username}
                        </p>
                        ${pwd.url ? `<p class="text-muted mb-0"><small><i class="bi bi-link-45deg"></i> ${pwd.url}</small></p>` : ''}
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewPassword(${pwd.id})">
                            <i class="bi bi-eye"></i> 查看
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deletePassword(${pwd.id})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 添加密码
function addPassword() {
    const data = {
        website: document.getElementById('password-website').value,
        username: document.getElementById('password-username').value,
        password: document.getElementById('password-password').value,
        category: document.getElementById('password-category').value,
        url: document.getElementById('password-url').value,
        notes: document.getElementById('password-notes').value
    };
    
    if (!data.website || !data.username || !data.password) {
        showAlert('请填写必填字段', 'warning');
        return;
    }
    
    fetch('/password/api/passwords', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('添加成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('addPasswordModal')).hide();
            document.getElementById('add-password-form').reset();
            loadPasswords();
        }
    });
}

// 查看密码
function viewPassword(id) {
    fetch(`/password/api/passwords/${id}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('view-website').textContent = data.website;
            document.getElementById('view-username').textContent = data.username;
            document.getElementById('view-password').value = data.password;
            
            if (data.url) {
                document.getElementById('view-url').href = data.url;
                document.getElementById('view-url').textContent = data.url;
                document.getElementById('view-url-container').style.display = 'block';
            } else {
                document.getElementById('view-url-container').style.display = 'none';
            }
            
            if (data.notes) {
                document.getElementById('view-notes').textContent = data.notes;
                document.getElementById('view-notes-container').style.display = 'block';
            } else {
                document.getElementById('view-notes-container').style.display = 'none';
            }
            
            new bootstrap.Modal(document.getElementById('viewPasswordModal')).show();
        });
}

// 复制密码
function copyPassword() {
    const password = document.getElementById('view-password').value;
    copyToClipboard(password);
}

// 切换密码可见性
function togglePasswordVisibility(inputId) {
    const input = document.getElementById(inputId);
    const icon = event.currentTarget.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'bi bi-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'bi bi-eye';
    }
}

// 删除密码
function deletePassword(id) {
    if (!confirm('确定要删除这个密码记录吗？')) return;
    
    fetch(`/password/api/passwords/${id}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            loadPasswords();
        }
    });
}

// 检测密码强度
document.getElementById('password-password')?.addEventListener('input', function() {
    const password = this.value;
    if (!password) {
        document.getElementById('password-strength').innerHTML = '';
        return;
    }
    
    fetch('/password/api/check-strength', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ password: password })
    })
    .then(response => response.json())
    .then(data => {
        const badge = `<span class="badge bg-${data.color}">${data.level}</span>`;
        const suggestions = data.suggestions.length > 0 
            ? `<small class="text-muted"> 建议: ${data.suggestions.join(', ')}</small>` 
            : '';
        
        document.getElementById('password-strength').innerHTML = 
            `密码强度: ${badge} ${suggestions}`;
    });
});

// 页面加载
document.addEventListener('DOMContentLoaded', function() {
    checkMasterPassword();
});
</script>
{% endblock %}

